﻿using System;
using System.Collections.Generic;
using System.Device.Location;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using ExifLib;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Controls.Maps;
using Microsoft.Phone.Controls.Maps.Platform;
using Microsoft.Phone.Info;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;

namespace PhotoMap
{
    public partial class MainPage : PhoneApplicationPage
    {
        public MainPage()
        {
            InitializeComponent();

        }

        #region private field
        private Pushpin _pushpin = null;
        private Pushpin _selfPushpin = null;
        #endregion

        #region override
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            Common.ResetSafelyTaskFlag();
            base.OnNavigatedTo(e);
        }
        #endregion

        #region private method

        /// <summary>
        /// 生成地图文件
        /// </summary>
        /// <param name="dlon"></param>
        /// <param name="dlat"></param>
        /// <param name="chosenPhoto"> </param>
        private void CreatePushpin(double dlon, double dlat, Stream chosenPhoto)
        {
            if (_pushpin != null)
            {
                myMap.Children.Remove(_pushpin);
            }

            _pushpin = new Pushpin
            {
                Location = new GeoCoordinate() { Latitude = dlat, Longitude = dlon },
                BorderBrush = new SolidColorBrush(Colors.Black),
                Style = Resources["PushpinStyle"] as Style,
            };

            var bmp = new BitmapImage();
            bmp.SetSource(chosenPhoto);

            _pushpin.Content = new Image()
            {
                Stretch = Stretch.Fill,
                Source = bmp,
            };
            myMap.Children.Add(_pushpin);
        }

        /// <summary>
        /// 获得用户当前的地理坐标
        /// </summary>
        private void GetGeoCoordinate()
        {
            (ApplicationBar.Buttons[0] as ApplicationBarIconButton).IsEnabled = false;
            loadingPanel.Visibility = Visibility.Visible;

            var thread = new Thread(() =>
                                        {
                                            var watcher = new GeoCoordinateWatcher();

                                            if (watcher.TryStart(false, TimeSpan.FromSeconds(3)))
                                            {
                                                Dispatcher.BeginInvoke(() =>
                                                                           {
                                                                               myMap.Center =
                                                                                   new GeoCoordinate(
                                                                                       watcher.Position.Location.
                                                                                           Latitude,
                                                                                       watcher.Position.Location.
                                                                                           Longitude);
                                                                               myMap.ZoomLevel = 10;
                                                                               CreateSelfPushpin(watcher);
                                                                           });

                                            }
                                            else
                                            {
                                                Dispatcher.BeginInvoke(() => MessageBox.Show("当前无法获得您的地理坐标，请稍后重试。"));
                                            }

                                            Dispatcher.BeginInvoke(() =>
                                                                       {
                                                                           loadingPanel.Visibility =
                                                                               Visibility.Collapsed;
                                                                           (ApplicationBar.Buttons[0] as
                                                                            ApplicationBarIconButton).IsEnabled = true;
                                                                       });
                                        });

            thread.Start();
        }

        /// <summary>
        /// 创建自己当前位置的坐标
        /// </summary>
        /// <param name="watcher"></param>
        private void CreateSelfPushpin(GeoCoordinateWatcher watcher)
        {
            //删除老坐标
            if (_selfPushpin != null)
            {
                myMap.Children.Remove(_selfPushpin);
            }

            //添加新坐标
            _selfPushpin = new Pushpin
            {
                Location =
                    new GeoCoordinate()
                    {
                        Latitude = watcher.Position.Location.Latitude,
                        Longitude = watcher.Position.Location.Longitude
                    },
                Background = new SolidColorBrush(Colors.Blue),
                Content = "Me",
            };
            myMap.Children.Add(_selfPushpin);
        }

        /// <summary>
        /// 选择照片
        /// </summary>
        private void ChoosePhoto()
        {
            PhotoChooserTask task = null;
            task = new PhotoChooserTask();

            task.ShowCamera = true;
            task.Completed += (s, ex) =>
            {
                if (ex.TaskResult == TaskResult.OK)
                {
                    var info = ExifReader.ReadJpeg(ex.ChosenPhoto, ex.OriginalFileName);
                    double DLat = 0;
                    double Dlon = 0;

                    if (info.GpsLatitude[0] > 0.0)
                    {
                        int num5 = 1;
                        if (info.GpsLatitudeRef != ExifGpsLatitudeRef.North)
                        {
                            num5 = -1;
                        }
                        DLat = num5 *
                               ((info.GpsLatitude[0] + (info.GpsLatitude[1] / 60.0)) +
                                ((info.GpsLatitude[2] / 60.0) / 60.0));

                        if (info.GpsLongitude[0] > 0.0)
                        {
                            int num6 = 1;
                            if (info.GpsLongitudeRef != ExifGpsLongitudeRef.East)
                            {
                                num6 = -1;
                            }
                            Dlon = num6 *
                                   ((info.GpsLongitude[0] + (info.GpsLongitude[1] / 60.0)) +
                                    ((info.GpsLongitude[2] / 60.0) / 60.0));

                            myMap.Center = new GeoCoordinate(DLat, Dlon);
                            CreatePushpin(Dlon, DLat, ex.ChosenPhoto);
                        }
                        else
                        {
                            MessageBox.Show("该照片没有经纬度信息");
                        }
                    }
                    else
                    {
                        MessageBox.Show("该照片没有经纬度信息");
                    }

                    //var bmp = new BitmapImage(new Uri(ex.OriginalFileName, UriKind.RelativeOrAbsolute));
                    //bmp.SetSource(ex.ChosenPhoto);

                    //openImage.Source = bmp;
                }
                //else if(ex.TaskResult == TaskResult.None)
                //{
                //    MessageBox.Show("打开相册失败，请断开手机与电脑的连接后重试。");
                //}
            };
            try
            {
                task.Show();
            }
            catch (Exception)
            {
                return;
            }
        }

        #endregion

        #region callback
        private void addPhotoApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            if (DeviceStatus.PowerSource == PowerSource.External)
            {
                MessageBox.Show("无法打开相册，请断开手机与电脑的连接后重试。", "提示", MessageBoxButton.OK);
                return;
            }

            ChoosePhoto();
        }


        private void locatePhotoApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            GetGeoCoordinate();
        }

        private void ButtonZoomIn_Click(object sender, RoutedEventArgs e)
        {
            myMap.ZoomLevel = (int)myMap.ZoomLevel + 1 >= 19 ? 19 : myMap.ZoomLevel + 1;
        }

        private void ButtonZoomOut_Click(object sender, RoutedEventArgs e)
        {
            myMap.ZoomLevel = (int)myMap.ZoomLevel - 1 <= 1 ? 1 : myMap.ZoomLevel - 1;
        }

        private void aboutApplicationBarMenuItem_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri(@"/About.xaml", UriKind.Relative));
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            //locateAppBar.IsEnabled = UserConfig.IsAllowLocate;
            (ApplicationBar.Buttons[0] as ApplicationBarIconButton).IsEnabled = UserConfig.IsAllowLocate;
        }

        private void optionPhotoApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri(@"/Option.xaml", UriKind.Relative));
        }

        #endregion
    }
}